package com.pwl.shiro.realm;

import com.pwl.shiro.entity.Roles;
import com.pwl.shiro.entity.Users;
import com.pwl.shiro.service.UsersService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    @Qualifier("usersService")
    private UsersService usersService;
//  授权器
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取已经通过认证的用户
        Users users=(Users) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        Set<String> permissions=new HashSet<>();
        //从登录的用户信息中提取角色信息
       users.getRoles().forEach(roles->{
           authorizationInfo.addRole(roles.getRolename());
           //从角色信息中提取权限列表
           roles.getPermissions().forEach(permissions1 -> {
             permissions.add(permissions1.getPtitle());
           });
       });
       authorizationInfo.addStringPermissions(permissions);


        return authorizationInfo;
    }

    //认证器
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username=token.getPrincipal().toString(); //登录时获取到的信息
        Users users= usersService.login(username);
        if (users==null){
            return null;
        }
        return new SimpleAuthenticationInfo(users,users.getUserpassword(), ByteSource.Util.bytes(users.getSalt()),getName());
    }
}
